﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

public class GameControl : MonoBehaviour {
    public GameObject gameover;
    private GameUI_Control gui;
    public Text scoreShow;
    public Text playingShow;
    public Text highestScore;
    public Sprite[] tiles;
    public Image NextTile;
    private int score;
    private bool isGameOver;
    private bool isPause;
    
    private void Start()
    {
        score = -1;
        gui = GetComponent<GameUI_Control>();
        AddScore();
        ShowPlaying();
        ShowHighestScore();
    }

    private void ShowPlaying()
    {
        playingShow.text = DataBase.Instance.NickName + " playing...";
    }
    private void ShowHighestScore()
    {
        highestScore.text = "历史最高分: " + DataBase.Instance.GetHighestScore();
    }

    void Update () {
        if (!isGameOver)
        {
            Playing();
        }
	}

    private void Playing()
    {
        if (!isPause)
        {
            if (Input.GetKeyDown(KeyCode.A))
            {
                gui.MoveBlock("left");
            }
            if (Input.GetKeyDown(KeyCode.D))
            {
                gui.MoveBlock("right");
            }
            if (Input.GetKeyDown(KeyCode.W))
            {
                gui.MoveBlock("rotate");
            }
            if (Input.GetKeyDown(KeyCode.S))
            {
                gui.SpeedUp();
            }
            else if (Input.GetKeyUp(KeyCode.S))
            {
                gui.SpeedDown();
            }
        }
    }

    internal void AddScore()
    {
        scoreShow.text = "Score：" + (++score);
    }
    internal void ShowNextTile(int x)
    {
        NextTile.sprite = tiles[x - 1];
        NextTile.SetNativeSize();
    }

    public void Pause()
    {
        Debug.Log("Pause");
        if (!isPause)
        {
            gui.CloseInvoke();
            gui.enabled = false;
            isPause = true;
        }
        else
        {
            gui.enabled = true;
            gui.SpeedDown();
            isPause = false;
        }
    }
    public void Quit()
    {
        Debug.Log("Quit");
        Application.Quit();
    }

    public void RePlay()
    {
        isGameOver = false;
        SceneManager.LoadSceneAsync("Play");
    }
    public void GoToScene0()
    {
        isGameOver = false;
        SceneManager.LoadSceneAsync(0);
    }

    internal void GameOver()
    {
        gui.CancelInvoke() ;
        gameover.SetActive(true);
        gui.enabled = false;
        if (!isGameOver)
        {
            DataBase.Instance.SaveScore(DataBase.Instance.NickName, score.ToString());
        }
        isGameOver = true;
    }
         

}
